const Koa = require('koa'); // koa
const app = new Koa(); // 实例
const router = require('@koa/router')() // 路由
const bodyParser = require('koa-bodyparser'); // 接收post传参
const cors = require('koa-cors') // 解决跨域
const global = require('./utils/mysql') // 数据库
const jwt = require('jsonwebtoken') // 生成token
const svgCaptcha = require('svg-captcha') // 验证码
const { koaBody } = require('koa-body');
let path = require('path')
const static = require('koa-static')

// 登录
router.post('/login', async ctx => {
    let { name, pwd } = ctx.request.body

    let res = await global.query(`select * from user where name = '${name}' and pwd = '${pwd}'`)
    if (res.length != 0) {
        let token = jwt.sign({ id: res.id, name: res.name }, 'byp', { expiresIn: '1h' })
        ctx.body = {
            code: 1,
            msg: "登录成功",
            token,
            data: res
        }
    } else {
        ctx.body = {
            code: 0,
            msg: "登录失败",
        }
    }
})

// 获取用户信息
router.post('/getuserinfo', async ctx => {
    let { uid } = ctx.request.body

    let res = await global.query(`select * from user where id = ${uid}`)
    ctx.body = {
        code: 1,
        msg: "获取用户信息成功",
        data: res
    }
})

// 上传头像
router.post('/upload', async ctx => {
    let { file } = ctx.request.files

    const url = `http://localhost:4000/${file.newFilename}`
    ctx.body = {
        code: 1,
        msg: "上传成功",
        avatar: url
    }
})

// 修改用户信息
router.post('/edituser', async ctx => {
    let { id, name, pwd, avatar } = ctx.request.body

    let res = await global.query(`update user set name = '${name}',pwd = '${pwd}', img = '${avatar}' where id = ${id}`)
    ctx.body = {
        code: 1,
        mag: '修改成功'
    }
})

let captchas = " ";

// 获取验证码
router.get('/getcaptcha', async ctx => {
    var captcha = svgCaptcha.create({
        size: 4,
        noise: 4,
        color: true,
        background: "#fff",
        width: 130,
        height: 32,
        fontSize: 40
    });
    captchas = captcha.text;
    ctx.response.type = 'svg';
    ctx.body = captcha.data;
})

// 注册
router.post('/register', async ctx => {
    let { name, pwd, captcha, img = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202106%2F22%2F20210622154903_3c36a.thumb.1000_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1686033111&t=9ccaa9e197838392ac20841d91003d78" } = ctx.request.body

    // 判断该用户是否存在
    let result = await global.query(`select * from user where name = '${name}'`)
    if (result.length == 1) {
        ctx.body = {
            code: 5,
            msg: '用户已存在！'
        }
        return;
    }

    // 验证验证码是否正确，如果错误，则返回错误信息。 如果正确，则执行注册
    if (captcha.toUpperCase() != captchas.toUpperCase()) {
        ctx.body = {
            code: 0,
            msg: "验证码不一致"
        }
        return;
    }

    // 注册
    let res = await global.query(`insert into user(name,pwd,img) values ('${name}','${pwd}','${img}')`)
    if (res.affectedRows == 1) {
        ctx.body = {
            code: 6,
            msg: '注册成功！'
        }
    } else {
        ctx.body = {
            code: 7,
            msg: '注册失败！'
        }
    }
})

// 获取菜单
router.get('/getmenu', async ctx => {
    let res = await global.query(`select * from menu`)
    ctx.body = {
        code: 0,
        msg: '获取成功',
        data: res
    }
})

// 添加菜单
router.post('/addmenu', async ctx => {
    let { name, type, icon, num, url = '', perms = '', parent_id } = ctx.request.body

    let res = await global.query(`insert into menu (name, url, perms, parent_id,num,icon,type) values ('${name}','${url}','${perms}',${parent_id},${num},'${icon}','${type}')`)
    if (res.affectedRows == 1) {
        ctx.body = {
            code: 1,
            message: '添加成功'
        }
    } else {
        ctx.body = {
            code: 0,
            message: '添加失败'
        }
    }
})

// 修改菜单
router.post('/editmenu', async ctx => {
    let { id, name, type, icon, num, url = '', perms = '', parent_id } = ctx.request.body

    let res = await global.query(`update menu set name='${name}', url='${url}', perms='${perms}', parent_id=${parent_id},num=${num},icon='${icon}',type='${type}' where id = ${id}`)
    if (res.affectedRows == 1) {
        ctx.body = {
            code: 1,
            message: '修改成功'
        }
    } else {
        ctx.body = {
            code: 0,
            message: '修改失败'
        }
    }
})

// 删除菜单
router.post('/delmenu', async ctx => {
    let { id } = ctx.request.body

    let res = await global.query(`delete from menu where id = ${id}`)
    ctx.body = {
        code: 1,
        msg: '删除成功',
    }
})

// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

// 获取角色
router.get('/getrole', async ctx => {
    let res = await global.query(`select * from role`)
    ctx.body = {
        code: 1,
        msg: '获取成功',
        data: res
    }
})

// 分页获取角色列表
router.post('/getmenelist', async ctx => {
    let { page, pagesize } = ctx.request.body
    let offset = (page - 1) * pagesize

    let res = await global.query(`select * from role limit ${offset},${pagesize}`)
    ctx.body = {
        code: 1,
        msg: "获取成功",
        data: res
    }

})

// 新增角色
router.post('/addrole', async ctx => {
    let { name, menulist } = ctx.request.body

    let res = await global.query(`insert into role(name,createTime) values('${name}',now())`)

    let rid = res.insertId
    // 添加关联权限
    let sql = `insert into role_menu(role_id,menu_id) values`
    menulist.map(item => {
        sql += `(${rid},${item}),`
    })
    let ind = sql.lastIndexOf(',')
    sql = sql.slice(0, ind)
    let reult = await global.query(sql)
    console.log(sql);
    ctx.body = {
        code: 1,
        msg: '新增成功',
    }
})

// 搜索角色
router.post('/searchrole', async ctx => {
    let { name } = ctx.request.body;

    let sql = `select * from role where 1 = 1`
    if (name != "") {
        sql += ` and name = '${name}'`
    }
    let res = await global.query(sql)
    ctx.body = {
        code: 1,
        msg: '查询成功',
        data: res
    }
})

// 修改角色
// router.post('/updaterole', async ctx => {
//     let { id, name, menulist } = ctx.request.body;

//     let res = await global.query(`update role set name='${name}' where id = ${id}`)

//     let sql = `update role_menu set`
//     menulist.map(item => {
//         sql += ` role_id = ${id},menu_id = ${item}`
//     })
//     sql += ` where role_id = ${id}`
//     console.log(sql);
// })

// 删除角色
router.post('/delrole', async ctx => {
    let { id } = ctx.request.body

    let res = await global.query(`delete from role where id = ${id}`)
    let result = await global.query(`delete from role_menu where role_id = ${id}`)

    ctx.body = {
        code: 1,
        msg: '删除成功'
    }
})

// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

// 获取管理员
router.get('/getadminlist', async ctx => {
    let res = await global.query(`select * from admin`)
    ctx.body = {
        code: 1,
        msg: '获取成功',
        data: res
    }
})

// 分页获取管理员列表
router.post('/getadmin', async ctx => {
    let { page, pagesize } = ctx.request.body
    let offset = (page - 1) * pagesize

    let res = await global.query(`select * from admin limit ${offset},${pagesize}`)
    ctx.body = {
        code: 1,
        msg: "获取成功",
        data: res
    }

})

// 新增管理员
router.post('/addadmin', async ctx => {
    let { name, email, phone, status, pass, img = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202106%2F22%2F20210622154903_3c36a.thumb.1000_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1686033111&t=9ccaa9e197838392ac20841d91003d78" } = ctx.request.body

    let res = await global.query(`insert into admin(name,email,phone,createTime,status) values('${name}','${email}','${phone}',now(),'${status}')`)
    let result = await global.query(`insert into user(name,pwd,img) values('${name}','${pass}','${img}')`)
    ctx.body = {
        code: 1,
        msg: '新增成功',
    }
})

// 搜索管理员
router.post('/searchadmin', async ctx => {
    let { name } = ctx.request.body;

    let sql = `select * from admin where 1 = 1`
    if (name != "") {
        sql += ` and name = '${name}'`
    }
    let res = await global.query(sql)
    ctx.body = {
        code: 1,
        msg: '查询成功',
        data: res
    }
})

// 修改管理员
router.post('/updateadmin', async ctx => {
    let { id, name, email, phone, status } = ctx.request.body;

    let res = await global.query(`update admin set name = '${name}', email ='${email}',phone = '${phone}',createTime = now(),status = '${status}' where id = ${id}`)
    ctx.body = {
        code: 1,
        msg: "修改成功"
    }
})

// 删除管理员
router.post('/deladmin', async ctx => {
    let { id } = ctx.request.body

    let res = await global.query(`delete from admin where id = ${id}`)
    let result = await global.query(`delete from user where id = ${id}`)
    ctx.body = {
        code: 1,
        msg: '删除成功'
    }
})

app.use(koaBody({
    multipart: true,
    formidable: {
        uploadDir: path.join(__dirname, './public'),
        keepExtensions: true,
        onError(err) {
            console.log(err);
        }
    }
}));

app.use(static(path.join(__dirname, './public')))
app.use(cors())
app.use(bodyParser());
app.use(router.routes());
app.use(router.allowedMethods());

app.use((ctx) => {
    ctx.body = `Request Body: ${JSON.stringify(ctx.request.body)
        }`;
});

app.listen(4000, () => {
    console.log("http://localhost:4000 后台服务器启动成功");
});